package org.thread.test02.demo04.demo1;

import java.io.*;

/**
 * @author ZJL
 * @date 2025-03-07
 */
public class UserThread extends Thread {
    /**
     * 源文件
     */
    private String source;
    /**
     * 目标文件
     */
    private String destination;
    /**
     * 拷贝文件的状态
     */
    private FileData fileData;


    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public FileData getFileData() {
        return fileData;
    }

    public void setFileData(FileData fileData) {
        this.fileData = fileData;
    }

    @Override
    public void run() {
        copyFile();
    }

    private void copyFile() {
        // 获取源文件对象
        File sourceFile = new File(this.source);
        // 获取目标文件对象
        File destinationFile = new File(this.destination);
        // 获取源文件对象的总容量
        long totalSize = sourceFile.length();
        this.fileData.setTotalSize(totalSize);

        // 实例化文件输入流、输出流的读和写
        try (
                FileInputStream fis = new FileInputStream(sourceFile);
                FileOutputStream fos = new FileOutputStream(destinationFile);
        ) {
            byte[] buffer = new byte[1];
            int size;
            int sum = 0;
            while ((size = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, size);
                sum += size;
                this.fileData.setCopiedSize(sum);
            }
            System.out.print("完成进度：100%");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
